﻿using System;
using System.Net.NetworkInformation;
using System.Windows;
using System.Windows.Controls;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;
using System.ServiceModel;
using PmuRegistry.Silverlight.ModalDialogs;
using System.Windows.Navigation;
using System.Windows.Media.Animation;
using System.Windows.Browser;

namespace PmuRegistry.Silverlight
{
	public partial class MasterLayoutControl : UserControl
	{
		PhasorDataServiceClient m_client;
		const double layoutRootHeight = 750;
		const double layoutRootWidth = 900;
		
		public MasterLayoutControl()
		{
			InitializeComponent();
			App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
			ContentFrame.Navigating += new System.Windows.Navigation.NavigatingCancelEventHandler(ContentFrame_Navigating);						
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetCompaniesCompleted += new EventHandler<GetCompaniesCompletedEventArgs>(client_GetCompaniesCompleted);
			m_client.GetNercRegionsCompleted += new EventHandler<GetNercRegionsCompletedEventArgs>(client_GetNercRegionsCompleted);
			m_client.GetInterconnectionsCompleted += new EventHandler<GetInterconnectionsCompletedEventArgs>(m_client_GetInterconnectionsCompleted);
			Loaded += new RoutedEventHandler(MasterLayoutControl_Loaded);
			NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
			ButtonLogout.Click += new RoutedEventHandler(ButtonLogout_Click);			
		}

		void m_client_GetInterconnectionsCompleted(object sender, GetInterconnectionsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxInterconnection.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Interconnections", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboBoxInterconnection.Items.Count > 0)
				ComboBoxInterconnection.SelectedIndex = 0;
		}

		void ButtonLogout_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonLogoutTransform);
			sb.Begin();

			((App)Application.Current).LoggedIn = false;

			string browserUrl = HtmlPage.Document.DocumentUri.ToString();
			browserUrl = browserUrl.Substring(0, browserUrl.IndexOf("#"));
			browserUrl = browserUrl.Replace("Home.aspx", "Default.aspx");			
			HtmlPage.Window.Navigate(new Uri(browserUrl));			
		}

		void Content_Resized(object sender, EventArgs e)
		{            
			ScaleContent(Application.Current.Host.Content.ActualHeight, Application.Current.Host.Content.ActualWidth);
		}
		
        void ScaleContent(double height, double width)
		{

            if ((bool)IsolatedStorageManager.LoadFromIsolatedStorage("MaintainAspectRatio"))
                StackPanelRoot.HorizontalAlignment = HorizontalAlignment.Center;                
            else
                StackPanelRoot.HorizontalAlignment = HorizontalAlignment.Left;

            //if (height > 0 && width > 0)
            //{
            //    LayoutRootScale.ScaleX = 0.98 * (width / layoutRootWidth);
            //    LayoutRootScale.ScaleY = 0.98 * (height / layoutRootHeight);
            //}
            double defaultHeight = IsolatedStorageManager.LoadFromIsolatedStorage("DefaultHeight") == null ? layoutRootHeight : Convert.ToDouble(IsolatedStorageManager.LoadFromIsolatedStorage("DefaultHeight"));
            double defaultWidth = IsolatedStorageManager.LoadFromIsolatedStorage("DefaultWidth") == null ? layoutRootWidth : Convert.ToDouble(IsolatedStorageManager.LoadFromIsolatedStorage("DefaultWidth"));
            double minimumHeight = IsolatedStorageManager.LoadFromIsolatedStorage("MinimumHeight") == null ? 600 : Convert.ToDouble(IsolatedStorageManager.LoadFromIsolatedStorage("MinimumHeight"));
            double minimumWidth = IsolatedStorageManager.LoadFromIsolatedStorage("MinimumWidth") == null ? 720 : Convert.ToDouble(IsolatedStorageManager.LoadFromIsolatedStorage("MinimumWidth"));

            if (height == 0) height = defaultHeight; //If for some reason, we dont get actual height and width then use default values.
            if (width == 0) width = defaultWidth;

            //if set to resize with browser then use actual height and width of the browser passed in the method parameters.
            if (IsolatedStorageManager.LoadFromIsolatedStorage("ResizeWithBrowser") != null && (bool)IsolatedStorageManager.LoadFromIsolatedStorage("ResizeWithBrowser"))
            {
                if (IsolatedStorageManager.LoadFromIsolatedStorage("MaintainAspectRatio") != null && (bool)IsolatedStorageManager.LoadFromIsolatedStorage("MaintainAspectRatio"))
                {
                    if (height / layoutRootHeight <= width / layoutRootWidth)
                    {
                        if (height < minimumHeight) height = minimumHeight;
                        LayoutRootScale.ScaleX = 0.98 * (height / layoutRootHeight);
                        LayoutRootScale.ScaleY = 0.98 * (height / layoutRootHeight);
                    }
                    else
                    {
                        if (width < minimumWidth) width = minimumWidth;
                        LayoutRootScale.ScaleX = 0.98 * (width / layoutRootWidth);
                        LayoutRootScale.ScaleY = 0.98 * (width / layoutRootWidth);
                    }
                }
                else
                {
                    if (height < minimumHeight) height = minimumHeight;
                    if (width < minimumWidth) width = minimumWidth;
                    LayoutRootScale.ScaleX = 0.98 * (width / layoutRootWidth);
                    LayoutRootScale.ScaleY = 0.98 * (height / layoutRootHeight);
                }
            }
            else	// if set not to resize with browser then, use default height and width to scale
            {
                if (defaultWidth < minimumWidth) defaultWidth = minimumWidth;
                if (defaultHeight < minimumHeight) defaultHeight = minimumHeight;

                LayoutRootScale.ScaleX = 0.98 * (defaultWidth / layoutRootWidth);
                LayoutRootScale.ScaleY = 0.98 * (defaultHeight / layoutRootHeight);
            }
		}

		void ContentFrame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
		{
			App app = Application.Current as App;
			if (!app.LoggedIn)
			{
				Uri loginUri = new Uri("/Pages/Login.xaml", UriKind.Relative);
				if (e.Uri != loginUri)
				{
					e.Cancel = true;
					ContentFrame.Navigate(loginUri);
				}
				ButtonLogout.Visibility = Visibility.Collapsed;				
			}
			else
			{
				ButtonLogout.Visibility = Visibility.Visible;
				if (ComboBoxCompany.Items.Count == 0)
					m_client.GetCompaniesAsync(true);
				if (ComboBoxNercRegion.Items.Count == 0)
					m_client.GetNercRegionsAsync(true);
				if (ComboBoxInterconnection.Items.Count == 0)
					m_client.GetInterconnectionsAsync(true);
			}
		}

		void client_GetNercRegionsCompleted(object sender, GetNercRegionsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxNercRegion.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve NERC Regions", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboBoxNercRegion.Items.Count > 0)
				ComboBoxNercRegion.SelectedIndex = 0;
		}

		void client_GetCompaniesCompleted(object sender, GetCompaniesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxCompany.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Companies", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboBoxCompany.Items.Count > 0)
				ComboBoxCompany.SelectedIndex = 0;
		}

		void ButtonChangeMode_Click(object sender, RoutedEventArgs e)
		{
			//if (!App.Current.IsRunningOutOfBrowser && App.Current.InstallState == InstallState.NotInstalled)
			//    App.Current.Install();
		}

		void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
		{
			if (NetworkInterface.GetIsNetworkAvailable())
			{
				//TextBlockConnectivity.Text = "Connected (online)";
				//TextBlockConnectivity.Foreground = new SolidColorBrush(Colors.Green);
			}
			else
			{
				//TextBlockConnectivity.Text = "Disconnected (offline)";
				//TextBlockConnectivity.Foreground = new SolidColorBrush(Colors.Red);
			}
		}

		void MasterLayoutControl_Loaded(object sender, RoutedEventArgs e)
		{
			if (App.Current.IsRunningOutOfBrowser)
			{
				//TextBlockExecutionMode.Text = "Out of Browser";
			}
			else
			{
				//TextBlockExecutionMode.Text = "In Browser";
			}
			if (NetworkInterface.GetIsNetworkAvailable())
			{
				//TextBlockConnectivity.Text = "Connected (online)";
				//TextBlockConnectivity.Foreground = new SolidColorBrush(Colors.Cyan);
			}
			else
			{
				//TextBlockConnectivity.Text = "Disconnected (offline)";
				//TextBlockConnectivity.Foreground = new SolidColorBrush(Colors.Red);
			}
			//client.GetCompaniesAsync(true);
			//client.GetNercRegionsAsync(true);
		}
	}
}
